/**
 * 解决 refreshToken 存在时，刷新token
 * */ 

import axios from 'axios';
import { setToken, setRefreshToken, getToken} from './token';
import { refreshToken, isRefreshRequest } from './refreshToken';

const ins = axios.create({
  baseURL: 'http://localhost:9527',
  headers: {
    Authorization: `Bearer ${getToken()}`
  }
});

ins.interceptors.response.use(async (res) => {
  if (res.headers.authorization) {  // 把服务器传的短期token 给保存下来
    const token = res.headers.authorization.replace('Bearer ', '');
    setToken(token)
    ins.defaults.headers.Authorization = `Bearer ${token}`
  }
  if(res.headers.refreshToken) { // 把服务器传的 长期token 给保存下来
    const refreshToken =  res.headers.authorization.replace('Bearer ', '');
    setRefreshToken(refreshToken)
  }
  if (res.data.code === 401){  // 仅针对 refresh 存在时，如果它不存在，死循环
    // 刷新token
    await refreshToken();
    // 重新请求
    res.config.headers.Authorization = `Bearer ${getToken()}`;
    const resp = await ins.request(res.config);
    return resp;
  }
  return res.data
})

export default ins;